import 'package:flutter/material.dart';
import '../services/database_service.dart';
import '../models/word.dart';
import '../models/question.dart';
import '../models/note.dart';
import '../models/essay_material.dart';
import '../models/practice_record.dart';
import '../models/check_in_record.dart';
import '../models/ai_chat_message.dart';

class DatabaseTestPage extends StatefulWidget {
  const DatabaseTestPage({Key? key}) : super(key: key);

  @override
  State<DatabaseTestPage> createState() => _DatabaseTestPageState();
}

class _DatabaseTestPageState extends State<DatabaseTestPage> {
  final DatabaseService _databaseService = DatabaseService();
  final List<String> _testResults = [];
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _initDatabase();
  }

  Future<void> _initDatabase() async {
    setState(() {
      _isLoading = true;
      _testResults.clear();
    });

    try {
      await _databaseService.init();
      _addResult('✅ 数据库初始化成功');
    } catch (e) {
      _addResult('❌ 数据库初始化失败: $e');
    }

    setState(() {
      _isLoading = false;
    });
  }

  void _addResult(String result) {
    setState(() {
      _testResults.add(result);
    });
  }

  Future<void> _testWordOperations() async {
    try {
      _addResult('\n🔤 测试单词操作...');
      
      // 添加单词
      final word = Word(
        id: 1,
        word: 'flutter',
        meaning: 'A UI toolkit for building natively compiled applications',
        translation: 'Flutter UI工具包',
        example: 'I am learning Flutter development.',
        category: 'Technology',
        difficulty: 2,
      );
      
      await _databaseService.wordRepository.addWord(word);
      _addResult('✅ 单词添加成功');
      
      // 查询单词
      final retrievedWord = await _databaseService.wordRepository.getWordById(1);
      if (retrievedWord != null && retrievedWord.word == 'flutter') {
        _addResult('✅ 单词查询成功');
      } else {
        _addResult('❌ 单词查询失败');
      }
      
      // 获取所有单词
      final allWords = await _databaseService.wordRepository.getAllWords();
      _addResult('✅ 获取所有单词: ${allWords.length} 个');
      
      // 更新单词
      final updatedWord = word.copyWith(meaning: 'Updated meaning');
      await _databaseService.wordRepository.updateWord(updatedWord);
      _addResult('✅ 单词更新成功');
      
    } catch (e) {
      _addResult('❌ 单词操作失败: $e');
    }
  }

  Future<void> _testQuestionOperations() async {
    try {
      _addResult('\n❓ 测试问题操作...');
      
      final question = Question(
        id: 1,
        question: 'What is Flutter?',
        optionA: 'A bird',
        optionB: 'A UI toolkit',
        optionC: 'A programming language',
        optionD: 'A database',
        correctAnswer: 'B',
        explanation: 'Flutter is a UI toolkit for building applications.',
        category: 'Technology',
        difficulty: 1,
        tags: 'flutter,ui,development',
        created_at: DateTime.now().millisecondsSinceEpoch,
        updated_at: DateTime.now().millisecondsSinceEpoch,
      );
      
      await _databaseService.questionRepository.addQuestion(question);
      _addResult('✅ 问题添加成功');
      
      final retrievedQuestion = await _databaseService.questionRepository.getQuestionById(1);
      if (retrievedQuestion != null) {
        _addResult('✅ 问题查询成功');
      } else {
        _addResult('❌ 问题查询失败');
      }
      
      final allQuestions = await _databaseService.questionRepository.getAllQuestions();
      _addResult('✅ 获取所有问题: ${allQuestions.length} 个');
      
    } catch (e) {
      _addResult('❌ 问题操作失败: $e');
    }
  }

  Future<void> _testNoteOperations() async {
    try {
      _addResult('\n📝 测试笔记操作...');
      
      final note = Note(
        id: 1,
        title: 'Flutter学习笔记',
        content: '今天学习了Flutter的基础知识，包括Widget、State等概念。',
        category: '学习',
        tags: 'flutter,学习,笔记',
        created_at: DateTime.now().millisecondsSinceEpoch,
        updated_at: DateTime.now().millisecondsSinceEpoch,
      );
      
      await _databaseService.noteRepository.addNote(note);
      _addResult('✅ 笔记添加成功');
      
      final retrievedNote = await _databaseService.noteRepository.getNoteById(1);
      if (retrievedNote != null) {
        _addResult('✅ 笔记查询成功');
      } else {
        _addResult('❌ 笔记查询失败');
      }
      
      final allNotes = await _databaseService.noteRepository.getAllNotes();
      _addResult('✅ 获取所有笔记: ${allNotes.length} 个');
      
    } catch (e) {
      _addResult('❌ 笔记操作失败: $e');
    }
  }

  Future<void> _testPracticeRecordOperations() async {
    try {
      _addResult('\n📊 测试练习记录操作...');
      
      final record = PracticeRecord(
        id: 1,
        questionId: 1,
        userAnswer: 'B',
        correctAnswer: 'B',
        isCorrect: true,
        timeSpent: 30,
        createdAt: DateTime.now().millisecondsSinceEpoch,
      );
      
      await _databaseService.practiceRecordRepository.addPracticeRecord(record);
      _addResult('✅ 练习记录添加成功');
      
      final allRecords = await _databaseService.practiceRecordRepository.getAllPracticeRecords();
      _addResult('✅ 获取所有练习记录: ${allRecords.length} 个');
      
      final allRecordsCount = allRecords.length;
         _addResult('✅ 练习记录总数: $allRecordsCount');
      
    } catch (e) {
      _addResult('❌ 练习记录操作失败: $e');
    }
  }

  Future<void> _runAllTests() async {
    setState(() {
      _isLoading = true;
      _testResults.clear();
    });

    await _testWordOperations();
    await _testQuestionOperations();
    await _testNoteOperations();
    await _testPracticeRecordOperations();

    _addResult('\n🎉 所有测试完成!');

    setState(() {
      _isLoading = false;
    });
  }

  Future<void> _clearAllData() async {
    try {
      setState(() {
        _isLoading = true;
      });

      await _databaseService.wordRepository.clearAllWords();
      await _databaseService.questionRepository.clearAllQuestions();
      await _databaseService.noteRepository.clearAllNotes();
      await _databaseService.practiceRecordRepository.clearAllPracticeRecords();

      _addResult('\n🗑️ 所有数据已清空');

      setState(() {
        _isLoading = false;
      });
    } catch (e) {
      _addResult('❌ 清空数据失败: $e');
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('IndexedDB 数据库测试'),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    onPressed: _isLoading ? null : _runAllTests,
                    child: const Text('运行所有测试'),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: ElevatedButton(
                    onPressed: _isLoading ? null : _clearAllData,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.red,
                      foregroundColor: Colors.white,
                    ),
                    child: const Text('清空所有数据'),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            if (_isLoading)
              const Center(
                child: CircularProgressIndicator(),
              ),
            Expanded(
              child: Container(
                width: double.infinity,
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey),
                  borderRadius: BorderRadius.circular(8),
                  color: Colors.grey[50],
                ),
                child: SingleChildScrollView(
                  child: Text(
                    _testResults.isEmpty 
                        ? '点击"运行所有测试"开始测试数据库功能'
                        : _testResults.join('\n'),
                    style: const TextStyle(
                      fontFamily: 'monospace',
                      fontSize: 14,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}